import config from '../../config';
import utils from '../../utils/util';
import WxValidate from '../../utils/WxValidate';
// https://kptest.ckjr001.com/kpv2p/lj7l/?#/homePage/form?cId=-1&extId=52478&ckFrom=12&isFromInvite=0&pId=&relType=19&type=1&isGoBack=1&specsType=1

//https://kptest.ckjr001.com/kpv2p/lj7l/?#/homePage/form?cId=-1&extId=52478&ckFrom=12&isFromInvite=0&pId=&relType=19&type=1&isGoBack=1&goodsRoomId=26557&specsType=1

// https://kptest.ckjr001.com/kpv2p/lj7l/?#/homePage/form?relId=7159&relType=1&type=2
let TcVod = require("../../utils/vod-wx-sdk-v2");
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    formList: {
      type: Object,
      value: {},
      observer: function (formList) {
        this._companyShare = utils.getStorage("companyShare");
        this.setData({
          addrPickerIndex: [], //地址索引
          isAddrHadPicker: false, //地址是否填写
        }, () => {
          this._formListInit(formList);
        })
      }
    },
    repeatCollect: { //是否可以重复采集
      type: Boolean,
      value: false
    },
    isAutoCollect: {
      type: Boolean,
      value: false
    },
    hadSubmit: {
      type: Boolean,
      value: false
    }
  },

  lifetimes: {
    attached: function () {
      this._provinceArr = [];
      this._cityArr = [];
      this._regionArr = [];

      this._provincesName = [];
      this._citysName = [];
      this._regionsName = [];

      this._currCityArr = [];
      this._currRegionArr = [];
      this._preHandData =null;
      this.getAreaAddrData();
      utils.get('imageSign').then(res => {
        this._aLiYunISP = res;
      });
    },
    detached: function () {}
  },

  /**
   * 组件的初始数据
   */
  data: {
    nationList: config.nationList,
    addrPickerArray: [], //地址
    addrPickerIndex: [], //地址索引
    isAddrHadPicker: false, //地址是否填写
    areaAddrData: [], //所有城市列表
    sexOption: ['男', '女'],
    dateYMDStart: "1900-01-01",
    dateYMDEnd: "2300-12-12",
    codeTime: 60
  },

  /**
   * 组件的方法列表
   */
  methods: {
    //表单提交
    formSubmit(e) {
      console.log("e", e, this.data.formList);
      let params = e.detail.value;
      console.log(params);
      if (!this._validateInstance.checkForm(params)) {
        const error = this._validateInstance.errorList[0];
        wx.showToast({
          title: error.msg,
          icon: "none",
        });
      } else {
        //表单验证通过，赋值formList（公众号的地址 value:详细地址 value2[省市区名称] value3[省市区id]）
        //通过以后要检查验证码是否正确，正确才提交表单（公众号的逻辑）
        let formList = this.data.formList;
        let phoneItem = this.data.formList.filter(item => item.type == 4)[0];
        // let formList = this._getMapSubmitParams(params);
        if (phoneItem) {
          const {
            relItem
          } = this._getFormItemAndIndx(phoneItem.id);
          if (relItem.isCheckTel) {
            //手机验证码
            this._checkPhoneCode(relItem.value, params[`${phoneItem.id}code`]).then(() => {
              this.triggerEvent("formSubmit", formList);
            })
          } else {
            this.triggerEvent("formSubmit", formList);
          }
        } else {
          this.triggerEvent("formSubmit", formList);
        }
      }
    },
    _formListInit(formList) {
      if (Array.isArray(formList)) {
        this._indexReduceCount = 0;
        formList.forEach((formItem, index) => {
          let showLogic = formItem.showLogic;
          let isHideByRel = false;
          let arrFlag = new Array(showLogic.length || 1).fill(true); //显示
          showLogic.forEach((showItem, index) => {
            if (showItem.id || showItem.id === 0) {
              const {
                relItem
              } = this._getFormItemAndIndx(showItem.id);
              console.log(`${formItem.title}-关联项`, relItem, formItem)
              if (showItem.condition == 0) {
                //未显示的时候  显示
                arrFlag = new Array(showLogic.length || 1).fill(relItem.isHideByRel ? true : false); //显示
              } else if (showItem.condition == 1) {
                //显示的时候 显示
                arrFlag = new Array(showLogic.length || 1).fill(!relItem.isHideByRel ? true : false); //显示
              } else if (showItem.condition == 2) {
                //未选中显示
                let val = [];
                if (relItem.type == 8 && relItem.multiple) {
                  //多选框
                  val = relItem.answerCheckbox || [];
                } else if (relItem.type == 8 && !relItem.multiple) {
                  val = [relItem.optIndex]
                }
                if (!val.length || relItem.isHideByRel) {
                  arrFlag[index] = true;
                  return;
                }
                if (Array.isArray(showItem.option)) {
                  let idx = v.option.findIndex(item => val.includes(item));
                  arrFlag[index] = idx == -1 ? true : false; //未选中显示  选中隐藏
                } else {
                  arrFlag[index] = val.includes(showItem.option) ? false : true; //未选中显示  选中隐藏
                }
              } else if (showItem.condition == 3) {
                //选中显示
                let val = [];
                if (relItem.type == 8 && relItem.multiple) {
                  //多选框
                  val = relItem.answerCheckbox || [];
                } else if (relItem.type == 8 && !relItem.multiple) {
                  val = [relItem.optIndex]
                }
                //选中显示
                if (!val.length) {
                  arrFlag[index] = false;
                  return;
                }
                if (Array.isArray(showItem.option)) {
                  //数组
                  let idx = showItem.option.findIndex(item => val.includes(item));
                  arrFlag[index] = idx == -1 ? false : true; //选项显示 没选中隐藏
                } else {
                  arrFlag[index] = val.includes(showItem.option) ? true : false; //选项显示 没选中隐藏
                }
              }
            }
          });
          if (formItem.showCondition == 1) {
            //全部满足
            isHideByRel = arrFlag.findIndex(val => val == false) == -1 ? false : true;
          } else {
            //满足一个条件
            isHideByRel = arrFlag.findIndex(val => val == true) == -1 ? true : false;
          }
          if (formItem.type == 6 && formItem.value3) {
            //地址
            let provinceId = formItem.value3.province * 1;
            let cityId = formItem.value3.city * 1;
            let areaId = formItem.value3.area * 1;
            let currCityChild = this._getCurrAddrChild(this._cityArr, provinceId);
            let currRegionChild = this._getCurrAddrChild(this._regionArr, cityId);
            this.data.addrPickerArray[1] = currCityChild.names;
            this.data.addrPickerArray[2] = currRegionChild.names;
            this._currCityArr = currCityChild.lists;
            this._currRegion = currRegionChild.lists;
            let provinceIndex = this._provinceArr.findIndex(item => item.value == provinceId);
            let cityIndex = this._currCityArr.findIndex(item => item.value == cityId);
            let areaIndex = this._currRegionArr.findIndex(item => item.value == areaId);
            console.log("areaIndex", areaIndex, areaId)
            let addrPickerIndex = [provinceIndex, cityIndex, areaIndex];
            this.setData({
              addrPickerArray: this.data.addrPickerArray,
              addrPickerIndex: addrPickerIndex
            })
            this._addrPickerIndexOld = addrPickerIndex;
          }
          if (formItem.type == 1 && !formItem.value && this.data.isAutoCollect) {
            formItem.value = this._companyShare.nickname;
          }
          if (formItem.showLogic.length, formItem.showLogic[0].id) {
            console.log(formItem.title, arrFlag, isHideByRel)
          }
          formItem.isHideByRel = isHideByRel;
          if (formItem.type == 10 || formItem.type == 15) {
            this._indexReduceCount++;
          }
          formItem.indexCount = index + 1 - this._indexReduceCount;
        });
        this.data.formList = formList;
        this.setData({
          formList: this.data.formList
        });
        this.data.formList.forEach(formItem => {
          if (formItem.type == 8) {
            if (formItem.multiple) {
              //多选
              this._toggleSkipOptions(formItem, formItem.answerCheckbox)
              this._toggleShowOptions(formItem, formItem.answerCheckbox);
            } else {
              //单选
              this._toggleSkipOptions(formItem, formItem.optIndex);
              this._toggleShowOptions(formItem, [formItem.optIndex]);
            }
          } else if (formItem.type == 14) {
            //下拉框
            this._toggleSkipOptions(formItem, formItem.optIndex);
            this._toggleShowOptions(formItem, [formItem.optIndex])
          } else if (formItem.type == 5) {
            this._toggleSkipOptions(formItem, formItem.value)
          }
        })
        this._initValidate();
      }
    },
    //检查验证码是否正确
    _checkPhoneCode(mobile, code) {
      return utils.post('k12/forms/checkCode', {
        mobile: mobile,
        code: code
      })
    },
    //获取手机验证码
    getPhoneCode(e) {
      let data = e.currentTarget.dataset.item;
      const {
        relItem
      } = this._getFormItemAndIndx(data.id);
      if (!/^1[3456789]\d{9}$/.test(relItem.value)) {
        wx.showToast({
          title: '请输入正确的手机格式',
          icon: 'none'
        });
        return;
      }
      if (this._phoneNumerTimer !== null) {
        clearTimeout(this._phoneNumerTimer);
      }
      this._phoneNumerTimer = setTimeout(() => {
        utils.post('k12/forms/sendCode', {
          mobile: relItem.value
        }).then(() => {
          wx.showToast({
            title: '验证码将在10分钟内有效！',
            icon: "none"
          })
          this._phoneCodeCountdown();
        })
      })
    },
    //获取验证码倒计时
    _phoneCodeCountdown: function () {
      this._codeTimer = setInterval(() => {
        this.setData({
          codeTime: this.data.codeTime - 1
        });
        if (this.data.codeTime < 1) {
          clearInterval(this._codeTimer);
          this.setData({
            codeTime: 60
          });
        };
      }, 1000)
    },
    bindinput(e) {
      let val = e.detail.value;
      let data = e.currentTarget.dataset.item;
      const {
        relItem
      } = this._getFormItemAndIndx(data.id);
      relItem.value = val;
    },

    //民族下拉选项
    nationPickerChange(e) {
      console.log(e);
      let val = e.detail.value * 1;
      let data = e.currentTarget.dataset.item;
      const {
        relItem
      } = this._getFormItemAndIndx(data.id);
      relItem.optIndex = val;
      relItem.value = this.data.nationList[val];
      this.setData({
        formList: this.data.formList
      });
    },
    //上传视频
    chooseUploadVideo(e) {
      let data = e.currentTarget.dataset.item;
      wx.chooseMedia({
        count: 1,
        mediaType: ['video'],
        sourceType: ['album', 'camera'], //从相册选择视频或者使用camera(相机摄像)
        success: (res) => {
          console.log("res", res);
          let resItem = res.tempFiles[0];
          let fileName = `xcxlive_${this._companyShare.encodeCompanyId}_form_${utils.uuid()}.${resItem.tempFilePath.split(".")[1]}`;
          const {
            relItem
          } = this._getFormItemAndIndx(data.id);
          this._videoUploading(resItem, fileName).then((res) => {
            relItem.value.title = relItem.value.title || relItem.title
            relItem.value.video = res.videoUrl;
            this.setData({
              formList: this.data.formList
            })
          })
        }
      })
    },
    //删除上传视频
    delUploadVideo(e) {
      let data = e.currentTarget.dataset.item;
      const {
        relItem
      } = this._getFormItemAndIndx(data.id);
      relItem.value.video = '';
      this.setData({
        formList: this.data.formList
      })
    },
    //上传图片
    chooseUploadPic(e) {
      let data = e.currentTarget.dataset.item;
      const {
        relItem
      } = this._getFormItemAndIndx(data.id);
      wx.chooseMedia({
        count: 9 - relItem.value.images.length,
        mediaType: ['image'],
        success: (res) => {
          this._picUploading(res.tempFiles, data, 0);
        },
      })
    },
    //删除上传图片
    delUploadPic(e) {
      let data = e.currentTarget.dataset.item;
      let index = e.currentTarget.dataset.index;
      const {
        relItem
      } = this._getFormItemAndIndx(data.id);
      relItem.value.images.splice(index, 1);
      this.setData({
        formList: this.data.formList
      })
    },
    //初始化验证配置
    // type: 1.姓名，2.微信号，3.年龄，4.手机号，5.性别，6.地址，7.职位，8.单选/多选，9.填空，10.图片跳转，11.上传图片，12.身份证，13.民族，14.下拉框，15.描述文字，16.日期，17.分隔 18.上传视频 
    _initValidate(formList = this.data.formList) {
      let rules = {},
        messages = {};
      formList.forEach((item, index) => {
        if (item.isHideByRel || item.type == 15 || item.type == 17 || item.type == 10) return;
        if (item.type == 3 && item.require) {
          //年龄
          rules[item.id] = {
            required: true,
            digits: true
          }
          messages[item.id] = {
            required: "请输入年龄",
            digits: "年龄必须是数字"
          }
        } else if (item.type == 4 && item.require) {
          //手机号必填
          rules[item.id] = {
            required: true,
            digits: true,
            minlength: 7,
          }
          messages[item.id] = {
            required: "请输入手机号",
            digits: "请输入数字",
            minlength: "手机号至少是7位数",
          }
        } else if (item.type == 6 && item.require) {
          //地址
          rules[`${item.id}AddrSelect`] = {
            required: true
          }
          messages[`${item.id}AddrSelect`] = {
            required: "请选择所在区域",
          }
          if (item.detailType == 1) {
            rules[`${item.id}AddrTextarea`] = {
              required: true
            }
            messages[`${item.id}AddrTextarea`] = {
              required: "请填写详细地址",
            }
          }
        } else if (item.type == 12 && item.require) {
          //身份证
          rules[item.id] = {
            required: true,
            minlength: 6
          }
          messages[item.id] = {
            required: "请输入身份证",
            minlength: "身份证不能小于6位"
          }
        } else if (item.type == 8 && item.require && item.isOtherOption && item.isShowOtherTextarea) {
          //单选 多选框 其他的选项的时候要 验证输入内容不为空
          rules[`${item.id}OtherTextarea`] = {
            required: true
          }
          messages[`${item.id}OtherTextarea`] = {
            required: `${item.title}不能为空`
          }
        } else if (item.require) {
          rules[item.id] = {
            required: true,
          }
          messages[item.id] = {
            required: `${item.title}不能为空`,
          }
        }
      });
      // console.log("_validateInstance", rules, messages)
      this._validateInstance = new WxValidate(rules, messages);
    },
    //签名
    _getTcVodSignature(callback) {
      let companyShare = utils.getStorage("companyShare");
      return utils.get('signCard/getVideoSign', {
        companyId: companyShare.encodeCompanyId
      }).then(res => {
        callback(res);
      })
    },
    //视频上传腾讯云
    _videoUploading(fileItem, fileName) {
      console.log(fileItem, fileName, TcVod);
      return new Promise((resolve, reject) => {
        console.log("xxxx", TcVod)
        wx.showLoading();
        TcVod.start({
          // 必填，把 wx.chooseVideo 回调的参数(file)传进来
          mediaFile: fileItem,
          // 必填，获取签名的函数
          getSignature: this._getTcVodSignature,
          // 选填，视频名称，强烈推荐填写(如果不填，则默认为“来自小程序”)
          mediaName: fileName,
          // 选填，视频封面，把 wx.chooseImage 回调的参数(file)传进来
          // coverFile: fileItem,
          // 上传中回调，获取上传进度等信息
          progress: function (result) {
            console.log('progress');
            console.log(result);
          },
          // 上传完成回调，获取上传后的视频 URL 等信息
          finish: function (result) {
            console.log('finish');
            console.log(result);
            wx.hideLoading();
            wx.showToast({
              title: '上传成功',
            })
            resolve(result);
          },
          // 上传错误回调，处理异常
          error: function (result) {
            wx.hideLoading();
            // console.log('error');
            console.log(result);
            // wx.showModal({
            //   title: '上传失败',
            //   content: JSON.stringify(result),
            //   showCancel: false
            // });
            reject();
          },
        });
      })
    },
    //图片上传
    _picUploading(data, formItem, index) {
      let item = data[index],
        nameCreate = `xcxlive_${this._companyShare.encodeCompanyId}_form_${utils.uuid()}.${item.tempFilePath.split(".")[1]}`;
      utils.upload({
        filePath: item.tempFilePath,
        ispInfo: this._aLiYunISP,
        nameCreate: nameCreate
      }).then((res) => {
        const {
          relItem
        } = this._getFormItemAndIndx(formItem.id);
        if (!Array.isArray(relItem.value.images)) {
          relItem.value.images = [];
        }
        relItem.value.title = relItem.value.title || relItem.title;
        relItem.value.images.push(res);
        console.log("relItem", relItem)
        this.setData({
          formList: this.data.formList
        }, () => {
          index++;
          if (index <= (data.length - 1)) {
            this._picUploading(data, formItem, index);
          }
        })
      }).catch(() => {
        //失败传下一张
        index++;
        if (index <= (data.length - 1)) {
          this._picUploading(data, formItem, index);
        }
      })
    },
    //日期选择事件
    dateYMDChange(e) {
      let data = e.currentTarget.dataset.item;
      console.log("dateYMDChange", e);
      const {
        relIndex,
        relItem
      } = this._getFormItemAndIndx(data.id);
      relItem.value = e.detail.value;
      this.data.formList[relIndex] = relItem;
      this.setData({
        formList: this.data.formList
      })
    },

    //性别选择(单选按钮组，可以关联滑到第几题)
    sexChange(e) {
      console.log(e);
      let data = e.currentTarget.dataset.item;
      const {
        relItem
      } = this._getFormItemAndIndx(data.id);
      relItem.value = Number(e.detail.value) ? '女' : '男';
      this.setData({
        formList: this.data.formList
      });
      this._toggleSkipOptions(data, relItem.value)
    },

    //通用下拉框选项
    selectPickerChange(e) {
      console.log(e);
      let data = e.currentTarget.dataset.item;
      let val = e.detail.value * 1;
      const {
        relItem
      } = this._getFormItemAndIndx(data.id);
      relItem.optIndex = val;
      relItem.value = [relItem.option[val].key];
      console.log(this.data.formList)
      this.setData({
        formList: this.data.formList
      });
      this._toggleSkipOptions(data, val);
      this._toggleShowOptions(data, [relItem.optIndex])
    },
    _toggleShowOptions(data, val = []) {
      console.log("_toggleShowOptions", data, val)
      let formList = this.data.formList;
      formList.forEach(formItem => {
        let showLogic = formItem.showLogic;
        let isHideByRel = false;
        let showLogicIds = [];
        showLogic.forEach(item => {
          if (item.id) {
            showLogicIds.push(item.id)
          }
        });
        if (!showLogicIds.includes(data.id) || data.isHideByRel) return;
        let arrFlag = new Array(showLogic.length || 1).fill(true); //显示
        showLogic.forEach((v, index) => {
          if (v.id == data.id) {
            console.log("formItem", formItem)
            const {
              relItem
            } = this._getFormItemAndIndx(v.id);
            if (v.condition == 0) {
              //未显示的时候  显示
              arrFlag = new Array(showLogic.length || 1).fill(relItem.isHideByRel ? true : false); //显示
            } else if (v.condition == 1) {
              //显示的时候  显示
              arrFlag = new Array(showLogic.length || 1).fill(!relItem.isHideByRel ? true : false); //显示
            } else if (v.condition == 2) {
              //不选中显示
              if (!val.length && !relItem.isHideByRel) {
                arrFlag[index] = true;
                return;
              }
              if (Array.isArray(v.option)) {
                let idx = v.option.findIndex(item => val.includes(item));
                arrFlag[index] = idx == -1 ? true : false; //未选中显示  选中隐藏
              } else {
                arrFlag[index] = (!val.includes(v.option) && !relItem.isHideByRel) ? true : false; //未选中显示  选中隐藏
              }
            } else if (v.condition == 3) {
              //选中显示
              if (!val.length || relItem.isHideByRel) {
                arrFlag[index] = false;
                return;
              }
              if (Array.isArray(v.option)) {
                //数组
                let idx = v.option.findIndex(item => val.includes(item));
                arrFlag[index] = idx == -1 ? false : true; //选项显示 没选中隐藏
              } else {
                arrFlag[index] = val.includes(v.option) ? true : false; //选项显示 没选中隐藏
              }
            }
          }
        });
        if (formItem.showCondition == 1) {
          //全部满足
          isHideByRel = arrFlag.findIndex(val => val == false) == -1 ? false : true;
        } else {
          //满足一个条件
          isHideByRel = arrFlag.findIndex(val => val == true) == -1 ? true : false;
        }
        formItem.isHideByRel = isHideByRel;
        this._toggleShowOptions(formItem)
        if (formItem.showLogic.length, formItem.showLogic[0].id) {
          console.log(formItem.title, arrFlag, isHideByRel)
        }
      });
      this.setData({
        formList: formList
      });
      this._initValidate();
    },
    //关联跳转跳转逻辑
    _toggleSkipOptions(data, val) {
      //skipLogic 跳转选项(中间折叠) 只能选择往后跳转（A显示-》B B显示判断是狗跳转C 递归
      if(data.isHideByRel) return;
      console.log("_toggleSkipOptions", data, val);
      //data在formList中的索引
      const chooseIdx = this._getFormItemAndIndx(data.id).relIndex;
      const skipLogic = data.skipLogic;
      let relateMaxIdx = 0;
      if (data.type == 8 && data.multiple == 1) {
        //复选多选(val是数组类型)  选有-1 全部显示（到max之间）
        let ids = [];
        skipLogic.forEach(item => {
          if (Array.isArray(val) && val.includes(item.option[0]) || (data.isShowOtherTextarea && item.option[0] == -2)) {
            //选中的项
            ids.push(item.id);
            let index = this._getFormItemAndIndx(item.id).relIndex;
            if (index > relateMaxIdx) relateMaxIdx = index;
          }
        });
        console.log("ids", ids)
        if (ids.includes(-1) && ids.length == 1) {
          //只有一个项规则  跳转到最后 就跳转
          this.data.formList.forEach((item, index) => {
            if (index > chooseIdx) {
              item.isHideByRel = true;
            }
          })
          return;
        } else {
          this.data.formList.forEach((item, index) => {
            if (index > chooseIdx) {
              item.isHideByRel = false;
            }
          })
        }
        if (!ids.length || ids.length > 1) {
          //全部显示,选中多个,一个都没选中
          this.data.formList.forEach((item, index) => {
            if (index > chooseIdx && index < relateMaxIdx) {
              item.isHideByRel = false;
            }
          })
        } else {
          //选中一个
          console.log("xxxxx-选中一个")
          let relateToIdx = this._getFormItemAndIndx(ids[0]).relIndex;
          this.data.formList.forEach((item, index) => {
            if (index > chooseIdx && index < relateToIdx) {
              item.isHideByRel = true;
            } else if (index > chooseIdx && index < relateMaxIdx) {
              item.isHideByRel = false;
            }
          })
        }
      } else {
        //其他
        let relateMaxIdx = 0;
        let ids = [];
        skipLogic.forEach(item => {
          if (item.id) {
            ids.push(item.id)
            let index = this._getFormItemAndIndx(item.id).relIndex;
            if (index > relateMaxIdx) relateMaxIdx = index;
          }
        });
        let selSkipItem = {};
        if (!!data.isOtherOption && data.isShowOtherTextarea) {
          //其他的选中
          selSkipItem = skipLogic.filter(item => item.option == -2 || item.option == val)[0] || {};
        } else {
          selSkipItem = skipLogic.filter(item => item.option == val)[0] || {};
        }
        if(this._preHandData && this._preHandData.id != data.id && this._preHandData.selId == -1) return;
        // if(this._isSkipEnd) return;
        console.log("ccccccccccc", selSkipItem, skipLogic, chooseIdx)
        if (selSkipItem.id == -1) {
          this._preHandData = {
            selId:selSkipItem.id,
            ...data,
          }
          this.data.formList.forEach((item, index) => {
            if (index > chooseIdx) {
              this.data.formList[index].isHideByRel = true;
            }
          });
          this.setData({
            formList: this.data.formList
          });
          return;
        } else if (selSkipItem.id != -1 && ids.includes(-1)) {
          this._preHandData = null;
          this.data.formList.forEach((item, index) => {
            if (index > chooseIdx) {
              item.isHideByRel = false;
            }
          });
        }
        if (selSkipItem.id) {
          let relateToIdx = this._getFormItemAndIndx(selSkipItem.id).relIndex;
          console.log("ccccccccccc", relateToIdx, chooseIdx)
          this.data.formList.forEach((item, index) => {
            if (index > chooseIdx && index < relateToIdx) {
              item.isHideByRel = true;
            } else if (index >= relateToIdx && index < relateMaxIdx) {
              item.isHideByRel = false;
            }
          })
        } else {
          this.data.formList.forEach((item, index) => {
            if (index > chooseIdx && index < relateMaxIdx) {
              item.isHideByRel = false
            }
          })
        }
      }
      this._initValidate();
      this.setData({
        formList: this.data.formList
      });

      setTimeout(() => {
        console.log("this.data.formList", this.data.formList)
      }, 2000)
    },
    _getFormItemAndIndx(id, formList = this.data.formList) {
      let resIndex = -1,
        resItem = null;
      for (let i = 0; i < formList.length; i++) {
        let item = formList[i];
        if (item.id == id) {
          resIndex = i;
          resItem = item;
          break;
        }
      }
      return {
        relIndex: resIndex,
        relItem: resItem
      };
    },

    //textarea 输入
    bindOtherTextareaInput(e) {
      console.log("e", e);
      let data = e.currentTarget.dataset.item;
      let val = e.detail.value;
      const {
        relItem
      } = this._getFormItemAndIndx(data.id);
      relItem.otherOption = val;
      this.setData({
        formList: this.data.formList
      })
    },
    //复选框
    checkboxBindChange(e) {
      console.log("checkboxBindChange", e);
      let valArr = e.detail.value;
      let data = e.currentTarget.dataset.item;
      let isOtherChoose = false;
      let sortValArr = [];
      const {
        relItem
      } = this._getFormItemAndIndx(data.id);
      relItem.answerCheckbox = [];
      valArr.forEach(k => {
        let idx = data._optionKeys.findIndex(item => item == k);
        if (idx != -1) {
          relItem.answerCheckbox.push(idx);
          relItem.answerCheckbox.sort();
        }
        if (data.option[idx].isOtherOption) {
          isOtherChoose = true;
        }
      });
      //选中顺序
      relItem.answerCheckbox.forEach(idx => {
        sortValArr.push(relItem.option[idx].key)
      });
      //设置选中
      console.log("relItem.answerCheckbox", relItem.answerCheckbox)
      relItem.option.forEach((item, index) => {
        if (relItem.answerCheckbox.includes(index)) {
          console.log("relItem.answerCheckbox", index)
          item.checked = true;
        } else {
          item.checked = false;
        }
      })
      if (isOtherChoose) {
        relItem.showOtherOption = true;
        relItem.isShowOtherTextarea = true;
      } else {
        relItem.showOtherOption = false;
        relItem.isShowOtherTextarea = false;
        relItem.otherOption = "";
      }
      this._initValidate();
      relItem.value = sortValArr;
      // relItem.option = relItem.option;
      console.log("this.data.formList", this.data.formList)
      this.setData({
        formList: this.data.formList
      });
      this._toggleSkipOptions(relItem, relItem.answerCheckbox)
      this._toggleShowOptions(relItem, relItem.answerCheckbox);
    },
    //单选按钮组
    radioBindChange(e) {
      console.log("radioBindChange", e);
      let data = e.currentTarget.dataset.item;
      let val = e.detail.value;
      const {
        relItem
      } = this._getFormItemAndIndx(data.id);
      let idx = relItem._optionKeys.findIndex(item => item == val);
      if (idx != -1) {
        relItem.optIndex = idx;
        if (relItem.option[idx].isOtherOption) {
          //其他选项选项
          relItem.isShowOtherTextarea = true;
        } else {
          relItem.otherOption = '';
          relItem.isShowOtherTextarea = false;
        }
        relItem.value = val;
      }
      this._initValidate();
      console.log(this.data.formList)
      this.setData({
        formList: this.data.formList
      });
      this._toggleSkipOptions(relItem, relItem.optIndex);
      this._toggleShowOptions(relItem, [relItem.optIndex]);
    },
    addrPickerConfirm(e) {
      console.log('picker发送选择改变，携带值为', e.detail.value);
      let data = e.currentTarget.dataset.item;
      let addrNames = this.data.addrPickerArray
      let idxs = e.detail.value;
      const {
        relItem
      } = this._getFormItemAndIndx(data.id);
      this.setData({
        isAddrHadChange: true,
        addrPickerIndex: idxs
      });
      relItem.value2 = {
        province: addrNames[0][idxs[0]],
        city: addrNames[1][idxs[1]],
        area: addrNames[2][idxs[2]]
      }
      relItem.value3 = {
        province: this._provinceArr[idxs[0]].value,
        city: this._currCityArr[idxs[1]].value,
        area: this._currRegionArr[idxs[2]].value
      };
      this.setData({
        formList: this.data.formList
      });
    },
    addrPickerColumnChange() {
      this._addrPickerIndexOld = [...this.data.addrPickerIndex];
      console.log('修改的列为', e.detail.column, '，值为', e.detail.value, this._addrPickerIndexOld);
    },
    addrPickerCancel() {
      console.log("bindAddrPickerCancel");
      let currCityChild = this._getCurrAddrChild(this._cityArr, this._provinceArr[this._addrPickerIndexOld[0]].value);
      let currRegionChild = this._getCurrAddrChild(this._regionArr, currCityChild.lists[0].value);
      this.data.addrPickerArray[1] = currCityChild.names;
      this.data.addrPickerArray[2] = currRegionChild.names;
      this._currCityArr = currCityChild.lists;
      this._currRegion = currRegionChild.lists;
      this.setData({
        addrPickerArray: this.data.addrPickerArray,
        addrPickerIndex: this._addrPickerIndexOld
      })
    },
    addrPickerColumnChange(e) {
      this._addrPickerIndexOld = [...this.data.addrPickerIndex];
      console.log('修改的列为', e.detail.column, '，值为', e.detail.value, this._addrPickerIndexOld);
      let data = {
        addrPickerArray: this.data.addrPickerArray,
        addrPickerIndex: this.data.addrPickerIndex
      }
      let currCityChild = {},
        currRegionChild = {};
      data.addrPickerIndex[e.detail.column] = e.detail.value;
      switch (e.detail.column) {
        case 0:
          currCityChild = this._getCurrAddrChild(this._cityArr, this._provinceArr[e.detail.value].value);
          currRegionChild = this._getCurrAddrChild(this._regionArr, currCityChild.lists[0].value);
          this._currCityArr = currCityChild.lists;
          this._currRegionArr = currRegionChild.lists;
          data.addrPickerArray[1] = currCityChild.names;
          data.addrPickerArray[2] = currRegionChild.names;
          data.addrPickerIndex[1] = 0;
          data.addrPickerIndex[2] = 0;
          break;
        case 1:
          currRegionChild = this._getCurrAddrChild(this._regionArr, this._currCityArr[e.detail.value].value);
          this._currRegionArr = currRegionChild.lists;
          data.addrPickerArray[2] = currRegionChild.names;
          data.addrPickerIndex[2] = 0;
          break;
      }
      this.setData(data)
    },
    _getCurrAddrChild(list, pid) {
      let res = {
        lists: [],
        names: [],
      };
      list.forEach(item => {
        if (item.parent == pid) {
          res.lists.push(item);
          res.names.push(item.name);
        }
      });
      // console.log("_getCurrAddrChild", res);
      return res;
    },
    //获取地址数据
    getAreaAddrData() {
      utils.get('common/getAreaListForAgent').then(res => {
        this.setData({
          areaAddrData: res.data
        });
        res.data.forEach(item => {
          if (item.level == 1) {
            this._provinceArr.push(item);
            this._provincesName.push(item.name);
          } else if (item.level == 2) {
            this._cityArr.push(item);
            this._citysName.push(item.name);
          } else if (item.level == 3) {
            this._regionArr.push(item);
            this._regionsName.push(item.name)
          }
        });
        let cityChild = this._getCurrAddrChild(this._cityArr, this._provinceArr[0].value);
        let regionChid = this._getCurrAddrChild(this._regionArr, cityChild.lists[0].value);
        this._currCityArr = cityChild.lists;
        this._currRegionArr = regionChid.lists;
        this.setData({
          addrPickerArray: [this._provincesName, cityChild.names, regionChid.names]
        });
        // this._addrPickerIndexOld = this.addrPickerIndex; //初始化前一次选择的值
        // console.log("address", this._provinceArr, this._provincesName, this._cityArr, this._citysName, this._regionArr, this._regionsName)
      })
    },
  }
})